﻿using Sunny.UI;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading;
using System.Windows.Forms;
using YunLuPos.Command;
using YunLuPos.DB.Service;
using YunLuPos.Entity;
using YunLuPos.Entity.Constant;
using YunLuPos.Printer;
using YunLuPos.Utils;
using YunLuPos.Worker;

namespace YunLuPos.SellView
{
    public partial class SellMainForm : UIForm
    {
        private log4net.ILog logger = log4net.LogManager.GetLogger(typeof(SellMainForm));
        private GoodsService goodsService = new GoodsService();
        private SaleOrderService orderService = new SaleOrderService();
        private SaleOrderGoodsService orderGoodsService = new SaleOrderGoodsService();
        private FileKeyBoardService keyBoardService = FileKeyBoardService.getService();
        private PromotionService promService = new PromotionService();
        private GroupPromotionService groupPromotionService = new GroupPromotionService();

        SellLoginFrom loginForm = null;
        public SellMainForm(SellLoginFrom loginForm)
        {
            InitializeComponent();
            this.loginForm = loginForm;
        }


        public SellMainForm()
        {
            InitializeComponent();
        }

        private void SellMainForm_Load(object sender, EventArgs e)
        {
            try
            {
                int w = Int32.Parse(StaticInfoHoder.Width);
                int h = Int32.Parse(StaticInfoHoder.Height);
                this.Width = w;
                this.Height = h;
                this.ShowTitle = (StaticInfoHoder.ShowTop == "1");
                if (StaticInfoHoder.FullScreen == "1")
                {
                    this.WindowState = FormWindowState.Maximized;
                }
                else
                {
                    this.WindowState = FormWindowState.Normal;
                }
            }
            catch
            {

            }
            this.topInfoPanel.uiPanel1.Style = this.Style;
            this.paymentPanel.uiPanel1.Style = this.Style;
            this.goodsInfoPanel.uiPanel1.Style = this.Style;
            this.preOrderInfoPanel.uiPanel1.Style = this.Style;
            this.uiMemberInfoPanel1.uiPanel1.Style = this.Style;
            this.uiWeightDisplayPanel1.uiPanel1.Style = this.Style;
            //初始化快捷菜单
            initShortPanel();
            //启动网络监测
            netCheckWorker.RunWorkerAsync();

            //启动重量监听
            initWeightWatcher();

            this.goodsGrid.AutoGenerateColumns = false;
            CommandManager.Exec(this, Names.BarCodeFocus.ToString());
            displayStaticInfo();
            createNewOrder();

            //清除3日前已上报数据
            try
            {
                orderService.cleanAll();
                logger.Info("清除3天前已上传单据");
            }
            catch (Exception ex)
            {
                //logger.Error("清除数据错误", ex);
            }
        }

        ComWeightWatcher watcher = null;
        void initWeightWatcher()
        {
            String enable = InIUtil.ReadInIData(InIUtil.WeightSection, InIUtil.W_ENABLE, "0");
            if ("1".Equals(enable))
            {
                watcher = new ComWeightWatcher();
                watcher.initWatcher(this);
                this.uiWeightDisplayPanel1.Visible = true;
            }else
            {
                this.uiWeightDisplayPanel1.Visible = false;
            }
        }

        /**
         * 初始化设置快捷方式
         * */
        void initShortPanel()
        {
            List<KeyBoard> btns = keyBoardService.listByHolder("主窗体");
            if (btns == null || btns.Count <= 0)
            {
                this.flowPanel.Visible = false;
                return;
            }
            else
            {
                this.flowPanel.Visible = true;
                btns.ForEach(l => {
                    if ("1".Equals(l.showTouch))
                    {
                        UIButton btn = new UIButton();
                        //btn.Style = UIStyle.Gray;
                        btn.Height = 25;
                        btn.Style = this.Style;
                        btn.Text =  l.commandName + "[" + l.keyCode + "]";
                        btn.Click += new System.EventHandler(this.ShortPanelButtonClick);
                        btn.Tag = l.keyCode;
                        btn.Font = new Font(btn.Font.FontFamily, 11);
                        Padding pad = new Padding(2, 0, 0, 3);
                        btn.Margin = pad;
                        this.flowPanel.Controls.Add(btn);
                    }
                });
                if (this.flowPanel.Controls.Count <= 0)
                {
                    this.Visible = false;
                }
            }
            //加载配置
            String showShort =  InIUtil.ReadInIData(InIUtil.GenSection, InIUtil.G_SHOW_SHORT, "1");
            if ("1".Equals(showShort))
            {
                this.showShortBar();
            }else
            {
                this.hideShortBar();
            }

        }
        //快捷按钮点击事件
        private void ShortPanelButtonClick(object sender, EventArgs e)
        {
            UIButton btn = (UIButton)sender;
            String tag = (String)btn.Tag;
            CommandManager.Exec(this, Names.BarCodeFocus.ToString());
            doCommand(tag);
        }


        private void SellMainForm_FormClosed(object sender, FormClosedEventArgs e)
        {
            if(watcher != null)
            {
                watcher.stopWatcher();
            }
            this.loginForm.Show();
        }

        /**
         * 显示静态信息
         * */
        void displayStaticInfo()
        {
            this.topInfoPanel.setCommInfo(StaticInfoHoder.commInfo);
        }

        /**
         * 创建一个新的单据
         * 并将当前单据设置为上一单
         * */
        public void createNewOrder(Boolean setPre = true)
        {
            //刷新前一单
            if (setPre)
            {
                DynamicInfoHoder.preOrder = DynamicInfoHoder.currentOrder;
                displayPreOrder();
            }
            SaleOrder order = orderService.createNewOrder(StaticInfoHoder.commInfo);
            DynamicInfoHoder.currentOrder = order;
            displayCurrentOrder(false, true);
        }

        /**
        * 刷新前一单据显示信息
        * */
        void displayPreOrder(Boolean fromdb = true)
        {
            SaleOrder order = DynamicInfoHoder.preOrder;
            if (fromdb && order != null)
            {
                DynamicInfoHoder.preOrder = orderService.getFullOrder(order.orderCode);
                order = DynamicInfoHoder.preOrder;
            }
            this.preOrderInfoPanel.setOrderInfo(order);
        }

        /**
        * 刷新当前单据显示信息
        * */
        public void displayCurrentOrder(Boolean fromdb = true, Boolean displayGoods = true)
        {
            SaleOrder order = DynamicInfoHoder.currentOrder;
            if (order != null && fromdb)
            {
                DynamicInfoHoder.currentOrder = orderService.getFullOrder(order.orderCode);
                order = DynamicInfoHoder.currentOrder;
            }
            if (displayGoods)
            {
                if (order.goods == null)
                {
                    this.goodsGrid.DataSource = new List<SaleOrderGoods>();
                }
                else
                {
                    this.goodsGrid.DataSource = order.goods;
                }
                //this.goodsGrid.CurrentCell
                //选中最后一行
                int last = this.goodsGrid.Rows.Count;
                if (last > 1)
                {
                    this.goodsGrid.CurrentCell = this.goodsGrid.Rows[last - 1].Cells[0];
                    
                }

                //刷新客显
                //显示客显
                if (order.goods != null)
                {
                    SaleOrderGoods goods = null;
                    if (order.goods.Count >= 1)
                    {
                        goods = order.goods.Get(order.goods.Count - 1);
                    }
                    if(goods != null)
                    {
                        try
                        {
                            
                            PrinterManager.getDisplayer().write(String.Format("{0:F2}", goods.disPrice),1);
                        }catch(Exception ex)
                        {
                            logger.Error("客显错误",ex);
                        }
                    }

                }
            }
            this.topInfoPanel.setOrderInfo(order);
            this.paymentPanel.setOrderInfo(order);
            if(order.memberNo != null && order.memberNo != "" && 
                order.memberName != null && order.memberName != "")
            {
                Member m = new Member();
                m.mebCode = order.memberNo;
                m.mebName = order.memberName;
                this.uiMemberInfoPanel1.setMebInfo(m);
            }else
            {
                this.uiMemberInfoPanel1.setMebInfo(null);
            }


        }
        /// <summary>
        /// 商品信息组件、扫码事件
        /// </summary>
        /// <param name="value"></param>
        /// <param name="handel"></param>

        private void goodsInfoPanel_CodeSearchEvent(string value, UIComponent.UIGoodsInfoPanel handel)
        {
            if ((value == null || "".Equals(value)))
            {
                CommandManager.Exec(this, Names.Payment.ToString());
                return;
            }
            Goods goods = goodsService.getGoodsByCode(value);
            if(goods == null)
            {
                goods = checkShortCode(value);
            }
            //显示单品
            handel.setGoods(goods);
           

            Boolean needApply = false;
            if (goods != null)
            {
                doNormGoods(goods);
            }else
            {
                //处理生鲜码解析
                needApply = !doWeightCode(value);
            }
            if (needApply)
            {
               // GoodsApply apply = new GoodsApply();
                //apply.ShowDialog();
            }
        }

        Boolean doWeightCode(String code)
        {
            if (code == null || "".Equals(code) || (code.Length != 13 && code.Length != 18))
            {
                //不符合生鲜码规则
                return false;
            }
            String barCode = code.Substring(0, 7);
            Goods goods = goodsService.getGoodsByCode(barCode);
            if(goods == null)
            {
                return false;
            }

            if (code.Length == 13)
            {
                //13位生鲜码检查是否存在活动、存在活动直接标记价格来源为活动价，实际单价以称为准
                Promotion prom = promService.getPromPrice(goods.barCode);
                Console.WriteLine(prom);
                //13位金额码
                String amtStr = code.Substring(7, 5);
                Double amt = Double.Parse(amtStr);
                amt = amt / 100;
                Double count = Math.Round(amt / goods.salePrice, 3);
                orderGoodsService.addGoods(DynamicInfoHoder.currentOrder, 
                    goods, 
                    count,
                    Double.NaN,
                    prom == null ? GoodsPriceSource.NORM : GoodsPriceSource.PROM,
                    null,
                    amt);
                
                ////修复称重码金额回算bug
                //orderGoodsService.addGoods(DynamicInfoHoder.currentOrder, goods, count);
            }
            else if(code.Length == 18)
            {
                //18位重量码
                //重量码在前，为18位重量码 
                Double count = Double.Parse(code.Substring(7, 5));
                if ("3".Equals(goods.saleType)){
                    //计数 处理托利多顶尖兼容问题，顶尖数量位在前两位，托利多数量位在后三位
                    if(count >= 1000)
                    {
                        //顶尖
                        count = (Int32)count / 1000;

                    }else
                    {
                        //托利多
                        //后两位数量无需处理
                    }
                }else
                {
                    //计重
                    count = Double.Parse(code.Substring(7, 5)) / 1000;
                    Console.WriteLine(count);
                }
                Double amt = Double.Parse(code.Substring(12, 5)) / 100;
                Double price = Math.Round(amt / count, 2);

                GoodsPriceSource gps = GoodsPriceSource.NORM;

                //价格模式
                String priceMode = InIUtil.ReadInIData(InIUtil.BalanceSection, InIUtil.BalancePriceMode, "1");
                if ("1".Equals(priceMode))
                {
                    //使用系统价高低统一计算优惠、有可能出现负优惠
                    if ((Math.Floor(goods.salePrice * 10)) != (Math.Floor(price * 10)))
                    {
                        gps = GoodsPriceSource.BALANCE;
                    }
                    //修复称重码金额回算bug
                    //orderGoodsService.addGoods(DynamicInfoHoder.currentOrder, goods, count,price,gps);
                    orderGoodsService.addGoods(DynamicInfoHoder.currentOrder, goods, count, price, gps, null, amt);
                }else if ("2".Equals(priceMode))
                {
                    //称台变价低使用称台价、称台变价高使用系统价 避免出现负优惠情况
                    if ((Math.Floor(goods.salePrice * 10)) > (Math.Floor(price * 10)))
                    {
                        //称台售价小于系统价、使用称台价
                        gps = GoodsPriceSource.BALANCE;
                        orderGoodsService.addGoods(DynamicInfoHoder.currentOrder, goods, count, price, gps, null, amt);
                    }
                    else
                    {
                        //称台价大于系统价、使用系统价、（不显示负优惠）
                        orderGoodsService.addGoods(DynamicInfoHoder.currentOrder, goods, count, price, gps, null, amt,true);
                    }
                    //修复称重码金额回算bug
                    //orderGoodsService.addGoods(DynamicInfoHoder.currentOrder, goods, count,price,gps);
                }else if ("3".Equals(priceMode))
                {
                    //使用称台价 最后一个参数强制使用外部价格
                    orderGoodsService.addGoods(DynamicInfoHoder.currentOrder, goods, count, price, gps, null, amt,true);
                }
                
            }
            displayCurrentOrder();
            return true;
        }

        /// <summary>
        /// 处理普通码扫描
        /// </summary>
        void doNormGoods(Goods goods)
        {
            //处理电子秤
            Double wCount = this.uiWeightDisplayPanel1.getWeight();
            //检查普通促销
            Promotion prom = promService.getPromPrice(goods.barCode);
            if (prom == null)
            {
                if (wCount != 0 && goods.saleType == "2")
                {
                    orderGoodsService.addGoods(DynamicInfoHoder.currentOrder, goods, wCount);
                }
                else
                {
                    orderGoodsService.addGoods(DynamicInfoHoder.currentOrder, goods);

                }
                //
                Boolean b = groupPromotionService.doGroupProm(DynamicInfoHoder.currentOrder);
            }
            else
            {
                if (wCount != 0 && goods.saleType == "2")
                {
                    orderGoodsService.addGoods(DynamicInfoHoder.currentOrder, goods, wCount, prom.promPrice, GoodsPriceSource.PROM, prom.promCode);
                }
                else
                {
                    orderGoodsService.addGoods(DynamicInfoHoder.currentOrder, goods, 1, prom.promPrice, GoodsPriceSource.PROM, prom.promCode);
                }
            }
            displayCurrentOrder();
        }

        /// <summary>
        /// 处理称码
        /// </summary>
        /// <param name="value"></param>
        /// <returns></returns>
        Goods checkShortCode(String value)
        {
            if(value == null || "".Equals(value))
            {
                return null;
            }
            if(value.Length > 5)
            {
                return null;
            }
            String code = "20" + value.PadLeft(5, '0');
            return goodsService.getGoodsByCode(code);
        }

        private void SellMainForm_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.KeyCode == Keys.D0 ||
              e.KeyCode == Keys.D1 ||
              e.KeyCode == Keys.D2 ||
              e.KeyCode == Keys.D3 ||
              e.KeyCode == Keys.D4 ||
              e.KeyCode == Keys.D5 ||
              e.KeyCode == Keys.D6 ||
              e.KeyCode == Keys.D7 ||
              e.KeyCode == Keys.D8 ||
              e.KeyCode == Keys.D9 ||
              e.KeyCode == Keys.Enter
               )
            {
                return;
            }
            if (e.KeyCode == Keys.Up)
            {
                this.moveUp();
            }
            else if (e.KeyCode == Keys.Down)
            {
                this.moveDown();
            }
            else
            {
                //Console.WriteLine(e.KeyCode);
                //按键操作方法
                doCommand(e.KeyCode.ToString());
            }
        }

        /**
       * 真实操作命令函数
       * */
        void doCommand(String keyCode)
        {
            KeyBoard kb = keyBoardService.getByKeyCode("主窗体", keyCode);
            if (kb != null)
            {
                CommandManager.Exec(this, kb.commandKey);
            }
        }

        /**
         * 下移选中行
         * 到最后一行停止
         * */
        public void moveUp()
        {
            if (goodsGrid.RowCount == 0)
            {
                return;
            }
            if (goodsGrid.CurrentRow.Index > 0)
            {
                int moveRow = goodsGrid.CurrentRow.Index - 1;
                goodsGrid.CurrentCell = goodsGrid.Rows[moveRow].Cells[0];
            }
        }

        /**
        * 上一选中行
        * 到第一行停止
        * */
        public void moveDown()
        {
            if (goodsGrid.RowCount == 0)
            {
                return;
            }
            if (goodsGrid.CurrentRow.Index < goodsGrid.RowCount - 1)
            {
                int moveRow = goodsGrid.CurrentRow.Index + 1;
                goodsGrid.CurrentCell = goodsGrid.Rows[moveRow].Cells[0];
            }
        }

        private void goodsInfoPanel_KeyDown(object sender, KeyEventArgs e)
        {

        }

        private void goodsGrid_Paint(object sender, PaintEventArgs e)
        {
           
        }

        private void goodsGrid_RowPostPaint(object sender, DataGridViewRowPostPaintEventArgs e)
        {
            System.Drawing.Rectangle rectangle = new System.Drawing.Rectangle(e.RowBounds.Location.X,
            e.RowBounds.Location.Y,
            this.goodsGrid.RowHeadersWidth - 4,
            e.RowBounds.Height);
            if (this.goodsGrid.CurrentRow != null)
            {
                TextRenderer.DrawText(e.Graphics, (e.RowIndex + 1).ToString(),
                      this.goodsGrid.RowHeadersDefaultCellStyle.Font,
                      rectangle,
                      (this.goodsGrid.CurrentRow != null && (e.RowIndex == this.goodsGrid.CurrentRow.Index)) ? Color.Black : Color.Black,
                      TextFormatFlags.VerticalCenter | TextFormatFlags.Right);

            }
        }

        private void goodsGrid_CellFormatting(object sender, DataGridViewCellFormattingEventArgs e)
        {
            if (goodsGrid.Columns["disAmount"].Index == e.ColumnIndex)
            {
                if (e.Value == null)
                {
                    return;
                }
                e.Value = Double.Parse(e.Value.ToString()).ToString("F2");
            }
            if (goodsGrid.Columns["priceSource"].Index == e.ColumnIndex)
            {
                if (e.Value == null)
                {
                    return;
                }
                if (GoodsPriceSource.NORM.ToString().Equals(e.Value))
                {
                    e.Value = "正常";
                }
                if (GoodsPriceSource.VIP.ToString().Equals(e.Value))
                {
                    e.Value = "会员价";
                }
                if (GoodsPriceSource.POS.ToString().Equals(e.Value))
                {
                    e.Value = "POS变价";
                }
                if (GoodsPriceSource.BALANCE.ToString().Equals(e.Value))
                {
                    e.Value = "称台价";
                }
                if (GoodsPriceSource.PROM.ToString().Equals(e.Value))
                {
                    e.Value = "普通促销";
                }
                if (GoodsPriceSource.GROUP_PROM.ToString().Equals(e.Value))
                {
                    e.Value = "组合促销";
                }
            }
        }

        public void lockPos()
        {
            loginForm.Show();
            loginForm.setLockInfo(StaticInfoHoder.commInfo.cashierCode);
            this.Hide();
        }

        private void netCheckWorker_DoWork(object sender, DoWorkEventArgs e)
        {
            while (true)
            {
                Thread.Sleep(1000);
                netCheckWorker.ReportProgress(1);
            }
        }

        private void netCheckWorker_ProgressChanged(object sender, ProgressChangedEventArgs e)
        {
            this.topInfoPanel.setNetStats(DynamicInfoHoder.netIsAlive);
        }

        private void netCheckWorker_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
        {

        }

        private void SellMainForm_FormClosing(object sender, FormClosingEventArgs e)
        {
            if(this.ShowAskDialog("退出系统", "确认退出收银台？", this.Style))
            {
                e.Cancel = false;
            }
            else
            {
                e.Cancel = true;
            }
        }

        /***
        * 代理更改界面参数，解决跨线程修改界面问题
        * */
        public void UpdateWeightText(string text)
        {
            if (this.InvokeRequired)
            {
                this.Invoke((Action)(delegate { UpdateWeightText(text); }));
            }
            else
            {
                this.uiWeightDisplayPanel1.setWeight(text);
            }
        }

        /**
         * 显示快捷键
         * */
        public void showShortBar()
        {
            this.shortPanel.Visible = true;
            this.goodsGrid.Width = this.Width - 119;
        }

        /**
         * 显示快捷键
         * */
        public void hideShortBar()
        {
            this.shortPanel.Visible = false;
            this.goodsGrid.Width = this.Width - 9;
        }

        private void SellMainForm_Shown(object sender, EventArgs e)
        {
            resetColWidth();
        }

        /// <summary>
        /// 根据表格大小重新计算每列宽度
        /// </summary>
        void resetColWidth()
        {
            double nameRate = 0.25;
            double barRate = 0.19;
            double priceRate = 0.09;
            double countRate = 0.09;
            double amoutRate = 0.09;
            double disRate = 0.09;
            int width = this.Width - 110;
            Console.WriteLine(width);
           
            // 重新计算宽度
            this.goodsGrid.Columns["goodsName"].Width = (int)(width * nameRate);
            this.goodsGrid.Columns["barCode"].Width = (int)(width * barRate);
            this.goodsGrid.Columns["disPrice"].Width = (int)(width * priceRate);
            this.goodsGrid.Columns["payAmount"].Width = (int)(width * countRate);
            this.goodsGrid.Columns["disAmount"].Width = (int)(width * amoutRate);
            this.goodsGrid.Columns["priceSource"].Width = (int)(width * disRate);
            
        }

        private void SellMainForm_ResizeEnd(object sender, EventArgs e)
        {
            
        }

        private void SellMainForm_Resize(object sender, EventArgs e)
        {
            resetColWidth();
        }
    }
}
